package com.dawn.module.hospital.service;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.framework.common.util.http.HttpUtils;
import com.dawn.module.hospital.controller.app.report.vo.ReportQueryDetailReqVO;
import com.dawn.module.hospital.controller.app.report.vo.ReportQueryReqVO;
import com.dawn.module.hospital.enums.BHConstants;
import com.dawn.module.hospital.util.XmlTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: cnsu-cmh
 * @time: 2024/8/8 18:06
 */
@Slf4j
@Service
public class ReportService extends BHService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PatientService patientService;


    @Autowired
    private EhealthService ehealthService;

    public CommonResult record(ReportQueryReqVO reqVO) {
        String type = reqVO.getReportType();
        String beginDate = reqVO.getStartDate().replaceAll("-","")+"000000";
        String endDate = reqVO.getEndDate().replaceAll("-","")+"235959";

        CommonResult patientResult = patientService.findPatientById(reqVO.getPId());
        JSONObject patient = (JSONObject)patientResult.getData();


        if(BHConstants.WEIXIN_SERVICE_ACCOUNTS.equals(reqVO.getAppType())) {
            // 上传数据到电子健康卡
            if(StringUtils.hasLength(getEhealthCfg().getHospitalId())) {
                try{
                    String ehealthCardId = patient.getString("ehealthCardId");
                    if(StringUtils.hasLength(ehealthCardId)) {
                        // TODO 上传数据到电子健康卡
                        String idCard = patient.getString("cardNo");
                        String scene;
                        if("check".equals(type)) {
                            scene="0101081";
                        } else {
                            scene="0101082";
                        }
                        ehealthService.uploadData(ehealthCardId,idCard,scene,null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        Map args = new HashMap();
        args.put("hisProvider",BHConstants.HIS_PROVIDER);
        args.put("patientId",patient.getString("patientId"));
//        args.put("patientId","629683");
        //类别，检查、检验、病理
//        args.put("type","0");
        //类型，1-门诊，2-住院，0-所有
        args.put("source","0");
        //挂号单据号 TYPE为1传挂号单号，2传住院次数 ,如果为空则获取该病人下所有的报告
        args.put("registerNo","");
        //页号：当前取第几页，记录按审核时间倒序排序
        args.put("pageNo","1");
        //记录数：每一页需返回的记录条数
        args.put("recNumber","10");
        args.put("checkDateStart",beginDate);//开始日期
        args.put("checkDateEnd",endDate);//结束日期
        args.put("type","检验");

        if("check".equals(type)) {
            //检查报告
            args.put("oldVersion",1);
            CommonResult httpResult = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_CHECK_RECORD.getValue(), args);
            return httpResult;
        } else {
            //检验报告
            CommonResult httpResult = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_TESTREP_RECORD.getValue(), args);
            JSONArray jsonArray = (JSONArray)httpResult.getData();

            JSONArray array = new JSONArray();
            if(jsonArray!=null && jsonArray.size()>0){
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String outReportDate = jsonObject.getString("outReportDate");
                    array.add(jsonObject);
//                    if(StringUtils.hasLength(outReportDate)){
//                        Date date = DateUtils.parseDate(outReportDate);
//                        if(end.compareTo(date)<0){
//                            array.add(jsonObject);
//                        }
//                    }else {
//                        array.add(jsonObject);
//                    }
                }
            }

            if(array.size()>0){
                return CommonResult.success(array);
            }else {
                return CommonResult.error(ERROR_CODE,"未查询到报告数据");
            }
        }
    }

    public CommonResult detail(ReportQueryDetailReqVO reqVO) {
        String xz = reqVO.getLx();
        Map args = new HashMap();
        args.put("hisProvider", BHConstants.HIS_PROVIDER);
        args.put("tradeSerialNumber", RandomUtil.randomNumbers(9));
        if("check".equals(reqVO.getReportType())) {
            //检查报告明细
            args.put("inReportNum",reqVO.getInReportID()); //  病历ID
            args.put("reprotId",reqVO.getInReportID());//  YZID
            CommonResult httpResult = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_CHECK_DETAIL.getValue(), args);
//            if(httpResult.isSuccess()){
//                JSONObject jsonObject = (JSONObject) httpResult.getData();
//                JSONArray array = jsonObject.getJSONArray("body");
//                if(array != null && array.size()>0){
//                    return CommonResult.success(array.get(0));
//                }
//            }
            return httpResult;
        }else {
            if(!StringUtils.hasLength(xz)){
                xz = "2";
            }
            //inReportID inReportNum  type  bgfl xz
            args.put("inReportID",reqVO.getInReportID());//  YZID
            args.put("inReportNum",reqVO.getInReportNum());//  BLID
            args.put("type",reqVO.getOutReportType());//  type
            args.put("bgfl","1");//  报告分类：0：老版方式病历id       1：新版报告编辑器影像id         2：专业版pacs返回RISID
            args.put("xz",xz);//  报告类型，检查报告时传空。检验报告时取报告记录中返回的LX，如果是通过4.3.4.2中的YZID查看报告，没有LX，则传2

            CommonResult apiResult = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_TESTREP_DETAIL.getValue(), args);

            if(apiResult.isError()) {
                return apiResult;
            }
            Map dataMap = (Map)apiResult.getData();
            Map<String, Object> testResult = XmlTools.dealJY_Xml(dataMap);
            return CommonResult.success(testResult);
        }
    }

}
